import { Redirect, Route, RouteProps } from "react-router-dom";
import { hasToken } from "@/utils/storage";

export interface ILoginState {
  fromPath?: string;
}

export interface IAuthRouteProps extends RouteProps {}
export function AuthRoute({
  path,
  component: Component,
  ...restProps
}: IAuthRouteProps) {
  if (!Component) return null;
  return (
    <Route
      {...restProps}
      path={path}
      render={(xxx) => {
        if (hasToken()) return <Component {...(xxx as any)} />;
        return (
          <Redirect
            to={{
              pathname: "/login",
              state: {
                fromPath: path,
              } as ILoginState,
            }}
          />
        );
      }}
    />
  );
}
